# -*- coding:utf-8 -*-
# __author__ = 'GuanFengyu'

import xlrd
import xlwt
import os

testdata_dir = r'D:\000_Git\GenerateTestCase\TestData'
testdata_name = 'demo.xlsx'
def read_sheet_by_col(workbook,sheetname):
    # 获取合并单元格的行列
    sheettext = workbook.sheet_by_name(sheetname)
    nrows = sheettext.nrows
    ncols = sheettext.ncols

    col_text = []
    for col in range(2,ncols):
        col_text.append(sheettext.col_values(col))



def read_sheet(workbook,sheetname):
    sheettext = workbook.sheet_by_name(sheetname)
    nrows = sheettext.nrows
    ncols = sheettext.ncols
    conditions = []
    results = []
    for crange in sheettext.merged_cells:
            rs, re, cs, ce = crange
            # rs,cs 读取方式不对
            if sheettext.cell_value(rs, cs) == u'条件桩':
                print(u'条件桩')
                print(rs,re,cs,ce)
                for col in range(cs + 2, ncols):
                    condition = []
                    for row in range(rs, re):
                        if sheettext.cell_value(row, col) == 'T':
                            condition += sheettext.cell_value(row,1)+';'
                        elif sheettext.cell_value(row, col) == 'F':
                            condition += u'不满足'+ sheettext.cell_value(row, 1)+';'
                        elif sheettext.cell(row, col).ctype == 0:
                            condition += sheettext.cell_value(row, 1)
                    condition[-1]='。'
                    conditions.append(condition)

                print(conditions)
                print('条件End')
            elif sheettext.cell_value(rs, cs) == u'动作桩':
                print(u'动作桩')
                for col in range(cs + 2, ncols):
                    for row in range(rs, re):
                        if sheettext.cell_value(row,col) == 'X':
                            results.append(sheettext.cell_value(row,1))
                print(results)
                print('动作End')
    return [conditions,results]

def read_excel():
    # 打开文件
    workbook = xlrd.open_workbook(os.path.join(testdata_dir,testdata_name))
    sheets = workbook.sheet_names()
    for sheet in sheets:
        conditions,results = read_sheet(workbook,sheet)
        # read_sheet_by_col(workbook,sheet)
        write_excel(sheet,conditions,results)
        break



def write_excel(sheet,conditions,results):
    wb = xlwt.Workbook(encoding='utf-8')
    booksheet = wb.add_sheet(sheet,cell_overwrite_ok=True)
    nrows = len(conditions)
    print(nrows)
    booksheet.write(0,0,'步骤描述')
    booksheet.write(0,1,'预期结果')
    for i in range(0,nrows):
        booksheet.write(i+1,0,conditions[i])
        booksheet.write(i+1,1,results[i])
    wb.save(os.path.join(testdata_dir,'testcases.xls'))


if __name__ == '__main__':
    read_excel()

